package com.atguigu.tingshu.payment.factory;

import com.atguigu.tingshu.payment.service.PaymentInfoService;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class PayFactoryImpl implements PayFactory, ApplicationContextAware {

    //支付渠道的bean的容器
    private Map<String, PaymentInfoService> payFactoryMap = new ConcurrentHashMap<>();

    /**
     * 构建好所有支付渠道的bean
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有指定类型的bean
        Map<String, PaymentInfoService> beansOfType =
                applicationContext.getBeansOfType(PaymentInfoService.class);
        //遍历存储
        beansOfType.entrySet().stream().forEach(entry->{
            //获取bean对象
            PaywayMark paywayMark = entry.getValue().getClass().getAnnotation(PaywayMark.class);
            //获取支付渠道
            String payway = paywayMark.payway();
            //存储
            payFactoryMap.put(payway, entry.getValue());
        });
    }

    /**
     * 获取具体支付渠道的实现类
     *
     * @param payway
     * @return
     */
    @Override
    public PaymentInfoService getPaymentInfoService(String payway) {
        return payFactoryMap.get(payway);
    }
}
